package com.hardydou.system.service.impl;

import ch.qos.logback.core.pattern.ConverterUtil;
import cn.hutool.core.util.StrUtil;
import com.hardydou.system.mapper.SystemResMapper;
import com.hardydou.system.mapper.SystemRoleMapper;
import com.hardydou.system.model.SystemRole;
import com.hardydou.system.service.ISystemRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ：hardy
 * @description：
 * @date ：Created in 2020-03-10
 * @Copyright ：Hardydou.com
 */
@Service
public class SystemRoleServiceImpl implements ISystemRoleService {

    @Autowired
    private SystemRoleMapper roleMapper;

    @Autowired
    private SystemResMapper resMapper;

    @Override
    public SystemRole findById(Long roleId) {

        return roleMapper.selectByPrimaryKey(roleId);
    }

    @Override
    public List<SystemRole> findAll(Map params) {
        return roleMapper.findAll(params);
    }

    @Override
    public int addRole(SystemRole role) {
        Date date = new Date();
        role.setUtime(date);
        role.setCtime(date);
        int n = roleMapper.insert(role);
        long[] resIds = StrUtil.splitToLong(role.getResIds(), ",");
        if (resIds.length > 0) {
            resMapper.bindToRole(role.getRoleId(), resIds);
        }
        return n;
    }

    @Override
    public int update(SystemRole role) {
        role.setUtime(new Date());
        int n = roleMapper.updateByPrimaryKeySelective(role);
        long[] resIds = StrUtil.splitToLong(role.getResIds(), ",");
        resMapper.unBindRole(role.getRoleId());
        if (resIds.length > 0) {
            resMapper.bindToRole(role.getRoleId(), resIds);
        }
        return n;
    }

    @Override
    public int deleteByRoleId(Long roleId) {
        resMapper.unBindRole(roleId);
        return roleMapper.deleteByPrimaryKey(roleId);
    }

}
